<!--详情-档案信息tab内容页-->
<template>
  <div class='archives flex-col'>
    <div class='flex-row' style='justify-content: space-between;'>
      <card-title text='档案信息'></card-title>
      <a-button type='primary' @click='downloadBatch'>批量导出</a-button>
    </div>
    <s-table
      ref='table'
      size='default'
      :rowKey='(record) => record.id'
      :columns='columns'
      :data='loadData'
      :showPagination='false'
    >
      <template slot='fileName' slot-scope='text, record'>
        <template v-if='record.pmDocData.length'>
          <!--          {{ record.pmDocData[0].fileEntityList.map(obj => obj.name).join(', ')}}-->
          <div class='flex-col'>
            <div class='flex-row' v-for='(item, i) in record.pmDocData[0].fileEntityList' :key='item.id'
                 style='justify-content: space-between;'>
              <a-button type='link' @click='downloadOne(item)'>{{ item.name }}</a-button>
              <a-popconfirm
                :title="'确定要删除文件 '+item.name+' 吗？'"
                ok-text='是'
                cancel-text='否'
                @confirm='confirmDelete(record, i)'
              >
                <a-icon type='close-circle' style='cursor: pointer;' />
              </a-popconfirm>
            </div>
          </div>
        </template>
        <span v-else>-</span>
      </template>
      <template slot='action' slot-scope='text, record'>
        <div class='flex-row'>
          <a-upload
            name='file'
            :multiple='false'
            :show-upload-list='false'
            :custom-request='(e)=>customRequest(e, record)'
            @change='handleChange'
          >
            <a-button type='link'>上传文档</a-button>
          </a-upload>
          <a-button type='link' @click='download(record)'>下载文档</a-button>
        </div>
      </template>
    </s-table>
  </div>
</template>

<script>
import CardTitle from '@/views/project/components/CardTitle.vue'
import { STable } from '@/components'
import { download, downloadAllDocData, downloadDocData, getDocData, saveDocData, upload } from '@/api/projectInitApply'
import moment from 'moment/moment'

export default {
  name: 'Archives',
  components: { CardTitle, STable },
  mounted() {
    // console.log(123)
    // localStorage.getItem("basicInfo")

  },
  props: {
    title: String
  },
  data() {
    return {
      tableData: [],
      columns: [
        {
          title: '阶段类型',
          width: 300,
          dataIndex: 'description',
          customRender: (value, row, index) => {
            let rowSpan = 0
            if (index === 0) {
              rowSpan = 8
            } else if (index >= 8 && index < 24) {
              if (index === 8) {
                rowSpan = 16
              } else {
                rowSpan = 0
              }
            } else if (index >= 24 && index < 31) {
              if (index === 24) {
                rowSpan = 7
              } else {
                rowSpan = 0
              }
            } else if (index >= 31 && index < 38) {
              if (index === 31) {
                rowSpan = 7
              } else {
                rowSpan = 0
              }
            }
            const calcCol = (index) => {
              if (index < 8) {
                return '立项阶段'
              } else if (index < 24) {
                return '实施阶段'
              } else if (index < 31) {
                return '验收阶段'
              } else {
                return '知识产权及成果'
              }
            }
            if (rowSpan !== 0) {
              return {
                children: calcCol(index),
                attrs: {
                  rowSpan: rowSpan
                }
              }
            }
            return {
              children: value,
              attrs: {
                rowSpan: rowSpan
              }
            }
          }
        },
        {
          title: '文档类型',
          dataIndex: 'docType',
          width: 300
        },
        {
          title: '文件名称',
          dataIndex: 'fileName',
          scopedSlots: { customRender: 'fileName' },
          align: 'center'
        },
        {
          title: '属性',
          dataIndex: 'docAttr',
          width: 100,
          customRender: (value, row, index) => {
            return value == 1 ? '必填' : ''
          }
        },
        {
          title: '上传人',
          width: 150,
          dataIndex: 'updatedBy',
          customRender: (value, row, index) => {
            if (row.pmDocData.length) {
              return row.pmDocData[0].createdBy
            } else return '-'
          }
        },
        {
          title: '上传时间',
          width: 200,
          dataIndex: 'updatedTime',
          customRender: (value, row, index) => {
            if (row.pmDocData.length) {
              return moment(row.pmDocData[0].createdTime).format('YYYY-MM-DD HH:mm:ss')
            } else return '-'
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 150,
          scopedSlots: { customRender: 'action' },
          align: 'center'
        }
      ],
      // 查询条件参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return getDocData({ projectId: this.$route.query.id }).then(res => {
          this.tableData = res.data
          return {
            pageSize: 1,
            pageNo: 1,
            data: res.data
          }
        })
      }
    }
  },
  methods: {
    customRequest({ file, onSuccess, onError }, record) {
      console.log(record)
      const formData = new FormData()
      formData.append('file', file)
      // formData.append('path', file.name)
      upload(formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        const pmDocDataList = record.pmDocData
        let pmDocData = {
          'fileIds': ''
        }
        if (pmDocDataList.length) {
          pmDocData = pmDocDataList[0]
        }
        let fileIds = ''
        if (pmDocData.fileIds.split(',')[0] !== '') {
          fileIds = [...pmDocData.fileIds.split(','), res.data].join(',')
        } else {
          fileIds = res.data
        }
        const params = {
          ...pmDocData,
          'directoryId': record.id,
          'fileIds': fileIds,
          'projectId': this.$route.query.id
        }
        saveDocData(params).then(res => {
          this.$refs.table.refresh(true)
        })
        onSuccess()
      })
    },
    confirmDelete(record, index) {
      const originList = record.pmDocData[0].fileIds.split(',')
      originList.splice(index, 1)
      const params = {
        ...record.pmDocData[0],
        'directoryId': record.id,
        'fileIds': originList.join(','),
        'projectId': this.$route.query.id
      }
      saveDocData(params).then(res => {
        this.$refs.table.refresh(true)
      })
    },
    handleChange(info) {
      const status = info.file.status
      if (status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (status === 'done') {
        this.$message.success(`${info.file.name} 上传成功.`)
      } else if (status === 'error') {
        this.$message.error(`${info.file.name} 上传失败.`)
      }
    },
    download(record) {
      console.log(record)
      if (record.pmDocData.length) {
        downloadDocData({ id: record.pmDocData[0].id }).then(res => {
          const file = new Blob(
            [res],
            { type: 'application/zip' }
          )
          const fileURL = URL.createObjectURL(file)
          const fileLink = document.createElement('a')
          fileLink.href = fileURL
          fileLink.setAttribute('download', this.title + '-' + record.docType)
          document.body.appendChild(fileLink)
          fileLink.click()
          URL.revokeObjectURL(fileURL)
          document.body.removeChild(fileLink)
        })
      }
    },
    downloadBatch() {
      downloadAllDocData({ projectId: this.$route.query.id }).then(res => {
        if (res) {
          const file = new Blob(
            [res],
            { type: 'application/zip' }
          )
          const fileURL = URL.createObjectURL(file)
          const fileLink = document.createElement('a')
          fileLink.href = fileURL
          fileLink.setAttribute('download', this.title || '档案信息')
          document.body.appendChild(fileLink)
          fileLink.click()
          URL.revokeObjectURL(fileURL)
          document.body.removeChild(fileLink)
        }
      })
    },
    downloadOne(item) {
      console.log(item)
      download({ url: item.url }).then((response) => {
        const file = new Blob(
          [response],
          { type: item.type }
        )
        const fileURL = URL.createObjectURL(file)
        const fileLink = document.createElement('a')
        fileLink.href = fileURL
        fileLink.setAttribute('download', item.name)
        document.body.appendChild(fileLink)
        fileLink.click()
        URL.revokeObjectURL(fileURL)
        document.body.removeChild(fileLink)
      })
        .catch((error) => {
          console.error('Download error:', error)
        })
    }
  }
}
</script>

<style scoped lang='less'>
.archives {
  background: #fff;
  width: 100%;
  padding: 20px;
}

.flex-row {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.flex-col {
  display: flex;
  flex-direction: column;
}
</style>